import Request from "../../../utils/request2.js";
import regeneratorRuntime from "../../../lib/js/runtime-module.js";
import util from "../../../utils/util2";
const app = getApp();
Component({
    // 组件自定义的属性
    properties: {
        //数据接收
        count: { //最多选择图片的张数，默认9张
            type: Number,
            value: 9
        },
        title: {
            type: String,
            value: ''
        },
        uploadFileName: {
            type: String,
            value: 'idCardPic'
        },
        fileName: {
            type: String,
            value: ''
        },
        bgImage:{
            type:String,
            value:''
        },
        status:{
            type:Boolean,
            value:false
        }
    },
    data: {
        uploadData: [],
        upNum: 0
    },
    //组件的方法列表
    methods: {
        //定义上传文件目录名字
        calculate_object_name(g_dirname, group, filename, isReal) {

            if (!filename) {
                return '';
            }
            function random_string(len) {
                len = len || 32;
                var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
                var maxPos = chars.length;
                var pwd = '';
                for (let i = 0; i < len; i++) {
                    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
                }
                return pwd;
            }

            function get_suffix(filename) {
                let pos = filename.lastIndexOf('.')
                let suffix = ''
                if (pos != -1) {
                    suffix = filename.substring(pos)
                }
                return suffix;
            }

            if (!!isReal) {
                if (!!group) {
                    return `${g_dirname}group/${filename}`
                } else {
                    return `${g_dirname}${filename}`
                }
            }

            let suffix = get_suffix(filename)
            let g_object_name = g_dirname + random_string(10) + suffix
            if (!!group) {
                if (g_dirname.indexOf('/') == -1) {
                    g_dirname += '/'
                }
                g_object_name = decodeURIComponent(g_dirname + group + '/' + (this.data.fileName ? this.data.fileName : random_string(10)) + suffix)
            }
            return g_object_name;
        },
        //图片预览
        previewImage(e) {
            let that = this;
            let uploadData = this.data.uploadData.map((res) => {
                return that.id ? res.url : res
            })
            if(uploadData.length==0){
                uploadData = [e.currentTarget.dataset.url]
            }
            wx.previewImage({
                current: e.currentTarget.dataset.url, // 当前显示图片的http链接
                urls: uploadData// 需要预览的图片http链接列表
            })

        },
        //上传服务器
        uploadFile(ele) {
            const that = this;
            const tokenData = wx.getStorageSync('tokenData');
            const fileUrlServer = that.calculate_object_name(tokenData.dir, that.data.uploadFileName, ele, false);
            return new Promise(function (resolve, reject) {
                wx.uploadFile({
                    url: tokenData.host,
                    filePath: ele,
                    name: 'file',
                    formData: {
                        name: ele,
                        key: fileUrlServer,
                        policy: tokenData.policy,
                        OSSAccessKeyId: tokenData.accessid,
                        success_action_status: '200',
                        signature: tokenData.signature,
                    },
                    success: function (res) {
                        const url = `${tokenData.host}/${fileUrlServer}`
                        resolve(url)
                    },
                    fail: function (errMsg) {
                        reject(errMsg)
                    }
                })
            })
        },
        //删除图片
        removeImg(e) {
            let index = e.target.dataset.index;
            let uploadData = this.data.uploadData;
            uploadData.splice(index, 1);
            this.setData({
                uploadData,
                upNum: uploadData.length
            });
            this.triggerEvent("uploadSuccess", uploadData);

        },
        //请求token
        getToken() {
            if (app.globalData.tokenStatus) {
                Request({ url: 'app/oss/token' }).then((res) => {
                    if (res.success) {
                        wx.setStorageSync('tokenData', res.extParams);
                        this.chooseImage();
                    }
                })
                app.globalData.tokenStatus = false
            }
        },
        //选择图片
        chooseImage() {
            const that = this;
            wx.chooseImage({
                count: this.data.count,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: function (res) {
                    let { uploadData } = that.data;
                    let filePaths = res.tempFilePaths;

                    if (that.data.count == 1) uploadData = [];//单张图片选择
                    for (let i = 0; i < filePaths.length; i++) {
                        that.uploadFile(filePaths[i]).then((url) => {
                            url=url+"?v="+new Date().getTime()
                            if (that.id) {
                                uploadData.push({ id: that.id, url: url });
                            } else {
                                uploadData.push(url);
                            }
                            that.setData({
                                uploadData,
                                upNum: uploadData.length
                            })
                            that.triggerEvent("uploadSuccess", uploadData);
                        });

                    }

                }
            })
        },
        //上传图片
        uploadImg: function (e) {
            //token有效值
            let getTokenValue = wx.getStorageSync('tokenData');
            if (getTokenValue && getTokenValue.expire) {
                let expireTokenTime = util.formatTimestamp(getTokenValue.expire, 'Y-M-D h:m:s');
                let isValidStatus = util.contrastDate(expireTokenTime);
                if (!isValidStatus) {
                    app.globalData.tokenStatus = true;
                    this.getToken();
                }
                else {
                    this.chooseImage();
                }
            } else {
                this.getToken();
            }

        },
    }
})
